<template>
  <div class="playback-integration-example">
    <h3>录像回放集成示例</h3>
    
    <!-- 控制面板 -->
    <div class="control-panel mb-4 p-4 bg-gray-100 rounded">
      <div class="flex gap-4 items-center">
        <!-- 日期选择 -->
        <div>
          <label class="block text-sm font-medium mb-1">选择日期</label>
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </div>
        
        <!-- 时间选择 -->
        <div>
          <label class="block text-sm font-medium mb-1">选择时间</label>
          <el-time-picker
            v-model="selectedTime"
            placeholder="选择时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            @change="handleTimeChange"
          />
        </div>
        
        <!-- 播放控制 -->
        <div class="flex gap-2">
          <el-button 
            type="primary" 
            @click="startPlayback"
            :loading="playbackStore.isLoadingStream"
            :disabled="!selectedDate || !selectedTime"
          >
            {{ playbackStore.isLoadingStream ? '获取流地址中...' : '开始播放' }}
          </el-button>
          
          <el-button 
            type="warning" 
            @click="stopPlayback"
            :disabled="!isPlaying"
          >
            停止播放
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 视频播放区域 -->
    <div v-if="isPlaying" class="video-playback-area">
      <div class="video-grid grid gap-4" :class="gridClass">
        <div 
          v-for="camera in playingCameras" 
          :key="camera.id"
          class="video-container border border-gray-300 rounded-lg overflow-hidden bg-black relative"
        >
          <!-- 摄像头信息覆盖层 -->
          <div class="camera-info-overlay absolute top-2 left-2 z-10 text-white">
            <div class="camera-name text-sm font-medium">{{ camera.name }}</div>
            <div class="camera-ip text-xs opacity-75">{{ camera.ip }}</div>
            <div class="playback-time text-xs opacity-75 mt-1">{{ formatTime(currentPlaybackTime) }}</div>
          </div>
          
          <!-- 流地址状态信息 -->
          <div class="stream-status-overlay absolute top-2 right-2 z-10 text-white">
            <div v-if="playbackStore.getCameraStreamUrl(camera.id.toString(), selectedDate, selectedTime)" class="stream-status">
              <div class="text-xs text-green-400">● 流地址已获取</div>
            </div>
            <div v-else-if="playbackStore.isLoadingStream" class="stream-status">
              <div class="text-xs text-yellow-400">● 正在获取流地址...</div>
            </div>
            <div v-else-if="playbackStore.streamError" class="stream-status">
              <div class="text-xs text-red-400">● 获取流地址失败</div>
            </div>
          </div>
          
          <!-- VideoPlayer 组件 -->
          <VideoPlayer
            :video-url="playbackStore.getCameraStreamUrl(camera.id.toString(), selectedDate, selectedTime)"
            :width="'100%'"
            :height="'100%'"
            :autoplay="true"
            :muted="true"
            :controls="false"
            :show-custom-controls="false"
            ref="videoPlayerRefs"
          />
        </div>
      </div>
    </div>
    
    <!-- 默认提示区域 -->
    <div v-else class="content-placeholder flex items-center justify-center h-64 text-gray-500">
      <div class="text-center">
        <el-icon class="text-6xl mb-4"><VideoCamera /></el-icon>
        <p>请选择日期和时间，然后点击开始播放</p>
      </div>
    </div>
    
    <!-- 调试信息 -->
    <div v-if="isPlaying" class="debug-info mt-4 p-4 bg-gray-50 rounded">
      <h4 class="font-medium mb-2">调试信息</h4>
      <div class="text-sm space-y-1">
        <div>播放模式: {{ playbackMode }}</div>
        <div>播放摄像头数量: {{ playingCameras.length }}</div>
        <div>当前时间: {{ selectedTime }}</div>
        <div>流地址缓存数量: {{ playbackStore.currentStreamUrls.size }}</div>
        <div v-if="playbackStore.streamError" class="text-red-500">
          错误信息: {{ playbackStore.streamError }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { ElDatePicker, ElTimePicker, ElButton, ElIcon } from 'element-plus'
import { VideoCamera } from '@element-plus/icons-vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import { usePlaybackStore } from '@/stores/playback'
import type { Device } from '@/types'

// Store
const playbackStore = usePlaybackStore()

// 状态变量
const selectedDate = ref('2025-10-14')
const selectedTime = ref('10:30:00')
const isPlaying = ref(false)
const playingCameras = ref<Device[]>([])
const playbackMode = ref<'sync' | 'async' | null>(null)
const currentPlaybackTime = ref(0)

// VideoPlayer组件引用
const videoPlayerRefs = ref<any[]>([])

// 模拟摄像头数据
const mockCameras: Device[] = [
  {
    id: 1,
    name: '摄像头1',
    nvrId: 1,
    subEquId: 1,
    equId: 0,
    ip: '192.168.1.100',
    port: 80,
    protocol: 'RTSP',
    status: 1,
    ptzEnable: false
  },
  {
    id: 2,
    name: '摄像头2',
    nvrId: 1,
    subEquId: 2,
    equId: 0,
    ip: '192.168.1.101',
    port: 80,
    protocol: 'RTSP',
    status: 1,
    ptzEnable: false
  }
]

// 计算属性
const gridClass = computed(() => {
  const count = playingCameras.value.length
  if (count === 1) return 'grid-cols-1'
  if (count === 2) return 'grid-cols-2'
  if (count >= 3) return 'grid-cols-2'
  return 'grid-cols-1'
})

// 方法
const startPlayback = async () => {
  try {
    console.log('开始播放录像...')
    
    // 设置播放状态
    isPlaying.value = true
    playingCameras.value = mockCameras
    playbackMode.value = 'sync'
    
    // 生成回放流地址
    await playbackStore.generateBatchPlaybackStreamUrls(
      mockCameras, 
      selectedDate.value, 
      selectedTime.value
    )
    
    console.log('录像播放开始')
    
  } catch (error) {
    console.error('播放失败:', error)
    isPlaying.value = false
    playingCameras.value = []
  }
}

const stopPlayback = () => {
  console.log('停止播放录像...')
  
  // 停止所有视频播放器
  videoPlayerRefs.value.forEach((playerRef, index) => {
    if (playerRef && playerRef.stopPlay) {
      console.log(`停止第${index + 1}个视频播放器`)
      playerRef.stopPlay()
    }
  })
  
  // 重置状态
  isPlaying.value = false
  playingCameras.value = []
  playbackMode.value = null
  
  // 清除流地址缓存
  playbackStore.clearStreamUrls()
  
  console.log('录像播放已停止')
}

const handleDateChange = (date: string) => {
  console.log('日期变化:', date)
  selectedDate.value = date
  
  // 如果正在播放，重新获取流地址
  if (isPlaying.value) {
    refreshStreamUrls()
  }
}

const handleTimeChange = (time: string) => {
  console.log('时间变化:', time)
  selectedTime.value = time
  
  // 如果正在播放，重新获取流地址
  if (isPlaying.value) {
    refreshStreamUrls()
  }
}

const refreshStreamUrls = async () => {
  try {
    console.log('重新获取流地址...')
    await playbackStore.generateBatchPlaybackStreamUrls(
      playingCameras.value, 
      selectedDate.value, 
      selectedTime.value
    )
    
    // 重新加载所有视频播放器
    nextTick(() => {
      videoPlayerRefs.value.forEach((playerRef, index) => {
        if (playerRef && playerRef.loadVideo) {
          console.log(`重新加载第${index + 1}个视频播放器`)
          playerRef.loadVideo()
        }
      })
    })
    
  } catch (error) {
    console.error('重新获取流地址失败:', error)
  }
}

const formatTime = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}
</script>

<style lang="scss" scoped>
.playback-integration-example {
  padding: 20px;
  
  .control-panel {
    .el-date-picker,
    .el-time-picker {
      width: 200px;
    }
  }
  
  .video-playback-area {
    .video-grid {
      .video-container {
        position: relative;
        min-height: 300px;
        
        .camera-info-overlay {
          background: rgba(0, 0, 0, 0.6);
          padding: 8px 12px;
          border-radius: 4px;
          backdrop-filter: blur(4px);
          
          .camera-name {
            font-weight: 600;
            margin-bottom: 2px;
          }
          
          .camera-ip {
            color: #d1d5db;
          }
          
          .playback-time {
            color: #9ca3af;
          }
        }
        
        .stream-status-overlay {
          background: rgba(0, 0, 0, 0.6);
          padding: 4px 8px;
          border-radius: 4px;
          backdrop-filter: blur(4px);
          
          .stream-status {
            text-align: right;
          }
        }
        
        // VideoPlayer 组件样式调整
        :deep(.video-player) {
          width: 100% !important;
          height: 100% !important;
          
          .video-container {
            width: 100% !important;
            height: 100% !important;
            
            video {
              width: 100% !important;
              height: 100% !important;
              object-fit: cover;
            }
          }
        }
      }
    }
  }
  
  .debug-info {
    font-family: monospace;
  }
}
</style>
